package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.github.pagehelper.util.StringUtil;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.core.domain.R;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.util.TimeZoneUtils;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import static com.zzyl.common.constant.CacheConstants.ALL_PRODUCT_KEY;

/**
 * 设备表Service业务层处理
 *
 * @author alexis
 * @date 2025-06-05
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private IoTDAClient iotDAClient;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 查询设备表
     *
     * @param id 设备表主键
     * @return 设备表
     */
    @Override
    public Device selectDeviceById(Long id) {
        return deviceMapper.selectById(id);
    }

    /**
     * 查询设备表列表
     *
     * @param device 设备表
     * @return 设备表
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备表
     *
     * @param device 设备表
     * @return 结果
     */
    @Override
    public int insertDevice(Device device) {
        return deviceMapper.insert(device);
    }

    /**
     * 修改设备表
     *
     * @param device 设备表
     * @return 结果
     */
    @Override
    public int updateDevice(Device device) {
        return deviceMapper.updateById(device);
    }

    /**
     * 批量删除设备表
     *
     * @param ids 需要删除的设备表主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids) {
        return deviceMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除设备表信息
     *
     * @param id 设备表主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id) {
        return deviceMapper.deleteById(id);
    }

    @Override
    public void syncProductList() {
        //读
        ListProductsRequest request = new ListProductsRequest();
        request.setLimit(50);
        ListProductsResponse Response = iotDAClient.listProducts(request);
        if (Response.getHttpStatusCode() != 200) {
            throw new BaseException("物联网接口 - 查询产品，同步失败");
        }
        List<ProductSummary> products = Response.getProducts();
        if (CollUtil.isEmpty(products)) {
            log.warn("物联网接口 - 获取产品列表为空");
            return;
        }
        //写
        redisTemplate.opsForValue().set(ALL_PRODUCT_KEY, JSONUtil.toJsonStr(Response.getProducts()));
    }

    @Override
    public List<ProductVo> getAllProduct() {
        String jsonStr = redisTemplate.opsForValue().get(ALL_PRODUCT_KEY);
        if (StringUtil.isEmpty(jsonStr)) {
            return Collections.emptyList();
        }
        return JSONUtil.toList(jsonStr, ProductVo.class);
    }

    @Override
    public void registerDevice(DeviceDto deviceDto) {
        if (deviceDto.getLocationType() == 0) {
            deviceDto.setPhysicalLocationType(-1);
        }
        //1. 判断设备名称是否重复
        Long count = lambdaQuery()
                .eq(Device::getDeviceName, deviceDto.getDeviceName())
                .count();
        if (count > 0) {
            throw new BaseException("设备名称重复");
        }
        //2. 判断设备标识是否重复
        count = lambdaQuery()
                .eq(Device::getNodeId, deviceDto.getNodeId())
                .count();
        if (count > 0) {
            throw new BaseException("设备标识码重复");
        }
        //3. 判断同一位置是否绑定了相同的产品
        count = lambdaQuery()
                .eq(Device::getBindingLocation, deviceDto.getBindingLocation())
                .eq(Device::getPhysicalLocationType, deviceDto.getPhysicalLocationType())
                .eq(Device::getProductKey, deviceDto.getProductKey())
                .eq(Device::getLocationType, deviceDto.getLocationType())
                .count();
        if (count > 0) {
            throw new BaseException("同一位置已绑定相同产品");
        }
        //4. 注册设备到华为iot平台
        //随机生成密钥
        String secret = UUID.randomUUID().toString().replace("-", "");
        AddDeviceRequest addDeviceRequest = new AddDeviceRequest();
        AddDevice addDevice = new AddDevice();
        addDevice.withNodeId(deviceDto.getNodeId())
                .withDeviceName(deviceDto.getDeviceName())
                .withProductId(deviceDto.getProductKey())
                .withAuthInfo(new AuthInfo().withSecret(secret));
        addDeviceRequest.withBody(addDevice);
        AddDeviceResponse response = null;
        try {
            response = iotDAClient.addDevice(addDeviceRequest);
        } catch (Exception e) {
            log.error("物联网接口 - 注册设备失败", e);
            throw new BaseException("物联网接口 - 注册设备失败");
        }
        //5.保存设备数据到数据库
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        device.setIotId(response.getDeviceId());
        device.setSecret(secret);
        save(device);
    }

    @Override
    public DeviceDetailVo queryDeviceDetail(String iotId) {
        //查询数据库
        Device device = lambdaQuery().eq(Device::getIotId, iotId).one();
        if (ObjectUtil.isEmpty(device)) {
            return null;
        }
        //查询华为iot平台
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.setDeviceId(iotId);
        ShowDeviceResponse response;
        try {
            response = iotDAClient.showDevice(request);
        } catch (Exception e) {
            log.error("物联网接口 - 获取设备详情失败", e);
            throw new BaseException("物联网接口 - 查询设备详情失败");
        }
        DeviceDetailVo deviceDetailVo = BeanUtil.toBean(device, DeviceDetailVo.class);
        deviceDetailVo.setDeviceStatus(response.getStatus());
        String activeTimeStr = response.getActiveTime();
        if (StringUtil.isNotEmpty(activeTimeStr)) {
            LocalDateTime activeTime = TimeZoneUtils.activeTime(activeTimeStr, DatePattern.UTC_MS_PATTERN);
            deviceDetailVo.setActiveTime(activeTime);
        }
        //封装返回
        return deviceDetailVo;
    }

    @Override
    public void updateDeviceById(DeviceDto deviceDto) {
        if (deviceDto.getLocationType() == 0) {
            deviceDto.setPhysicalLocationType(-1);
            deviceDto.setDeviceDescription(String.valueOf(deviceDto.getBindingLocation()));
        }
        Device deviceone = selectDeviceById(deviceDto.getId());
        //1. 判断设备名称是否重复
        Long count = lambdaQuery()
                .ne(Device::getId, deviceDto.getId())
                .eq(Device::getDeviceName, deviceDto.getDeviceName())
                .count();
        if (count > 0) {
            throw new BaseException("设备名称重复");
        }
        //2. 判断同一位置是否绑定了相同的产品
        count = lambdaQuery()
                .ne(Device::getId, deviceDto.getId())
                .eq(Device::getBindingLocation, deviceDto.getBindingLocation())
                .eq(Device::getPhysicalLocationType, deviceDto.getPhysicalLocationType())
                .eq(Device::getProductKey, deviceDto.getProductKey())
                .eq(Device::getLocationType, deviceDto.getLocationType())
                .count();
        if (count > 0) {
            throw new BaseException("同一位置已绑定相同产品");
        }
        //修改iot平台
        UpdateDeviceRequest requst = new UpdateDeviceRequest();
        requst.setDeviceId(deviceDto.getIotId());
        requst.setBody(new UpdateDevice().withDeviceName(deviceDto.getDeviceName()));
        try {
            UpdateDeviceResponse Response = iotDAClient.updateDevice(requst);
        } catch (Exception e) {
            log.error("物联网接口 - 修改设备失败", e);
            throw new BaseException("物联网接口 - 修改设备失败");
        }
        //修改数据库
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        updateById(device);
    }

    @Override
    public void deleteDeviceByiotId(String iotId) {
        //删除iot平台
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.setDeviceId(iotId);
        DeleteDeviceResponse response;
        try {
            response = iotDAClient.deleteDevice(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 删除设备失败");
        }
        // 删除数据库中的设备记录
        Device device = lambdaQuery().eq(Device::getIotId, iotId).one();
        removeById(device);
    }

    @Override
    public AjaxResult queryServiceProperties(String iotId) {
        //查询iot平台
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.setDeviceId(iotId);
        ShowDeviceShadowResponse response;
        try {
            response = iotDAClient.showDeviceShadow(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 查询设备影子失败");
        }
        List<DeviceShadowData> shadow = response.getShadow();
        //判断设备影子是否为空
        if (ObjectUtil.isEmpty(shadow)){
            List<Object> emptyList  = Collections.emptyList();
            //如果是空返回数据
            return AjaxResult.success(emptyList);
        }
        JSONObject jsonObject = JSONUtil.parseObj(shadow.get(0).getReported().getProperties());
        //日期时区转换
        LocalDateTime eventTime = TimeZoneUtils.activeTime(shadow.get(0).getReported().getEventTime(), "yyyyMMdd'T'HHmmss'Z'");
        List<Map<String, Object>> list = new ArrayList<>();
        jsonObject.forEach((key, value) -> {
            Map<String, Object> map = new HashMap<>();
            map.put("functionId", key);
            map.put("value", value);
            map.put("eventTime", eventTime);
            list.add(map);
        });

        //封装返回
        return AjaxResult.success(list);
    }

    @Override
    public AjaxResult queryProduct(String productKey) {
        if (StringUtil.isEmpty(productKey)){
            throw new BaseException("产品Key不能为空");
        }
        ShowProductRequest request = new ShowProductRequest();
        request.setProductId(productKey);
        ShowProductResponse response;
        try {
            response = iotDAClient.showProduct(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 查询产品失败");
        }
        List<ServiceCapability> serviceCapabilities = response.getServiceCapabilities();
        if (serviceCapabilities == null){
            return AjaxResult.success(Collections.emptyList());
        }
        return AjaxResult.success(serviceCapabilities);
    }
}
